﻿using Furion.Schedule;
using JQData.Core.DbModel;
using JQData.Core.TushareSDK;
using JQData.Core.TushareSDK.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JQData.Application.Jobs
{
    public class DataSync : IJob
    {
        private readonly ILogger<DataSync> _logger;
        private readonly IConfiguration _configuration;
        private readonly IServiceScopeFactory _scopeFactory;

        public DataSync(ILogger<DataSync> logger
            , IConfiguration configuration
            , IServiceScopeFactory scopeFactory)
        {
            _logger = logger;
            _configuration = configuration;
            _scopeFactory = scopeFactory;
        }

        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            using var serviceScope = _scopeFactory.CreateScope();

            _logger.LogInformation($"{context}");
            await 同步名录(serviceScope);
            await 同步股票(serviceScope);
            await 同步游资交易(serviceScope);
            await Task.CompletedTask;
        }

        public async Task 同步名录(IServiceScope serviceScope)
        {
            var repository = serviceScope.ServiceProvider.GetService<IRepository<HotMoney>>();

            var core = new TushareCore("d6bd5319b55741d52682b9586bca1bccd72e9649840c41760fe5eea3");
            var api = new OtherApi(core);

            var res = await api.GetHmListAsync();

            foreach (var item in res)
            {
                var dbModel = await repository.FirstOrDefaultAsync(i => i.Name == item.Name);

                if (dbModel != null)
                {
                    if (dbModel.Desc != item.Desc || dbModel.Orgs != item.Orgs)
                    {
                        _logger.LogError($"游资名录{dbModel.Name},内容不一样{dbModel.Desc} | {item.Desc} || {dbModel.Orgs} | {item.Orgs}");

                        dbModel.Orgs = item.Orgs;
                        dbModel.Desc = item.Desc;
                        dbModel.UpdatedTime = DateTimeOffset.Now;
                        await repository.SaveNowAsync();
                        _logger.LogError($"游资名录{dbModel.Name},同步异常，内容不一样{dbModel.Desc == item.Desc} {dbModel.Orgs == item.Orgs}");
                    }

                }
                else
                {
                    dbModel = new HotMoney()
                    {
                        Name = item.Name,
                        Orgs = item.Orgs,
                        Desc = item.Desc,
                        CreatedTime = DateTimeOffset.Now,
                    };
                    repository.Insert(dbModel);
                    await repository.SaveNowAsync();
                }



            }
        }


        public async Task 同步股票(IServiceScope serviceScope)
        {

            var repository = serviceScope.ServiceProvider.GetService<IRepository<StockBasic>>();

            var core = new TushareCore("d6bd5319b55741d52682b9586bca1bccd72e9649840c41760fe5eea3");
            var api = new StockApi(core);

            var res = await api.GetStockBasicAsync(ListingStatus.上市);
            var res2 = await api.GetStockBasicAsync(ListingStatus.暂停上市);
            var res3 = await api.GetStockBasicAsync(ListingStatus.退市);
            res.AddRange(res2);
            res.AddRange(res3);
            foreach (var item in res)
            {
                await 同步单只股票(repository, item);
            }


        }


        public async Task 同步单只股票(IRepository<StockBasic> db, StockBaseResult item)
        {
            var dbModel = db.FirstOrDefault(i => i.TsCode == item.TsCode);
            if (dbModel == null)
            {
                dbModel = item.Adapt<StockBasic>();
                // L上市 D退市 P暂停上市

                dbModel.CreatedTime = DateTimeOffset.Now;
                dbModel.UpdatedTime = DateTimeOffset.Now;
                db.Insert(dbModel);
            }
            else
            {
                //如果存在
                dbModel.Name = item.Name;
                dbModel.Area = item.Area;
                dbModel.Industry = item.Industry;
                dbModel.FullName = item.FullName;
                dbModel.EnName = item.EnName;
                dbModel.Cnspell = item.Cnspell;
                dbModel.Market = item.Market;
                dbModel.Exchange = item.Exchange;
                dbModel.CurrType = item.CurrType;
                dbModel.DelistDate = item.DelistDate;
                dbModel.IsHS = item.IsHS;
                dbModel.ActEntType = item.ActEntType;
                dbModel.ActName = item.ActName;
                dbModel.UpdatedTime = DateTimeOffset.Now;
            }

            dbModel.ListingStatus = item.ListingStatus switch
            {
                "L" => ListingStatus.上市,
                "D" => ListingStatus.退市,
                "P" => ListingStatus.暂停上市,
                _ => dbModel.ListingStatus // 保持原值（默认或Adapt已设置的值）
            };


            await db.SaveNowAsync();
        }


        public async Task 同步游资交易(IServiceScope serviceScope)
        {
            var tradeDb = serviceScope.ServiceProvider.GetService<IRepository<HotMoneyTrade>>();
            var hotMoneyDb = serviceScope.ServiceProvider.GetService<IRepository<HotMoney>>();
            var stockBasicDb = serviceScope.ServiceProvider.GetService<IRepository<StockBasic>>();


            var core = new TushareCore("d6bd5319b55741d52682b9586bca1bccd72e9649840c41760fe5eea3");
            var api = new OtherApi(core);

            var hotMoneyList = await hotMoneyDb.Entities.ToListAsync();

            //查询出最后时间
            var startDate = await tradeDb.Entities.OrderByDescending(i => i.Date)
                                      .Select(i => i.Date).FirstOrDefaultAsync();
            if (startDate < new DateOnly(2022, 8, 1))
            {
                startDate = new DateOnly(2022, 9, 1);
            }
            else
            {
                startDate = startDate.AddDays(-1);
            }

            //startDate = new DateOnly(2022, 8, 1);
            for (int i = 0; i < 1000; i++)
            {
                await 同步游资交易_每日(startDate.AddDays(i), api, hotMoneyList, stockBasicDb, tradeDb);
            }


        }

        public async Task 同步游资交易_每日(DateOnly day, OtherApi api,
            List<HotMoney> hotMoneyList, IRepository<StockBasic> stockBasicDb
            , IRepository<HotMoneyTrade> tradeDb)
        {
            var res = await api.GetHmDetailAsync(day);

            if (res.Count > 0)
            {
                foreach (var item in res)
                {
                    var hotMoney = hotMoneyList.FirstOrDefault(i => i.Name == item.HmName);
                    var stock = await stockBasicDb.FirstOrDefaultAsync(i => i.TsCode == item.StockCode);
                    if (hotMoney == null || stock == null)
                    {
                        //continue;
                        _logger.LogError($"游资名录或股票不存在，游资名录：{item.StockName}，股票代码：{item.StockCode}");
                        continue;
                        //throw new Exception($"游资名录或股票不存在，游资名录：{item.StockName}，股票代码：{item.StockCode}");
                    }


                    var linq = tradeDb.Where(i => i.Date == item.Date)
                                               .Where(i => i.StockId == stock.Id)
                                               .Where(i => i.HotMoneyId == hotMoney.Id);

                    if (!await linq.AnyAsync())
                    {
                        var dbModel = new HotMoneyTrade()
                        {
                            Date = item.Date,
                            StockId = stock.Id,
                            StockCode = item.StockCode,
                            StockName = item.StockName,
                            BuyAmount = item.BuyAmount,
                            SellAmount = item.SellAmount,
                            NetAmount = item.NetAmount,
                            HmName = hotMoney.Name,
                            HmOrgs = hotMoney.Orgs,
                            Tag = hotMoney.Desc,
                            HotMoneyId = hotMoney.Id,
                            CreatedTime = DateTimeOffset.Now,
                            UpdatedTime = DateTimeOffset.Now
                        };
                        await tradeDb.InsertNowAsync(dbModel);
                    }
                }
                Console.WriteLine(day);
            }


        }

    }
}
